import urllib2
import datetime
import ChartResult
from Utility import Utility

class ChartResults:
    
    def __init__(self):
        self._columns = ("Close", "High", "Low", "Open", "Volume", "Up", "Change", "Range", "Diff")    
        self._address = "http://www.google.com/finance/getprices?i={0}&p={1}d&f=d,o,h,l,c,v&df=cpct&q={2}"

      
    def Get(self, ticker, period, days):
        try:
            self._ticker = ticker
            self._period = period
            self._days = days
            url = self._address.format(period, days, ticker)
            self._sum = ChartResult.ChartResult(self)
            lines = urllib2.urlopen(url)
            self._exchange = Utility.SubstringAfter(lines.readline())
            self._marketOpenMinute = int(Utility.SubstringAfter(lines.readline(),'='))
            d = int(Utility.SubstringAfter(lines.readline(),'=').strip('a')) / 86400 + 25569 + 693594 + (5.5 / 24) 
            self._start = datetime.datetime.fromtimestamp(d)
            self._interval = Utility.SubstringAfter(lines.readline(),'=')
            self._values = list()
            
            Utility.RemoveNumLines(lines, 3)
            isFirstRow = True
            for line in lines:
                result = ChartResult.ChartResult(self)
                result.Update(self._start, self._marketOpenMinute, self._interval, line, isFirstRow, self._sum)
                isFirstRow = False
                self._values.append(result)
                #print(line)
                
            self._header = "Ticker {0} ({1}), Period {2}, Days {3}, Open {4}, High {5}, Low {6}, Close {7}, Vol {8}".format( 
                                  self._ticker, self._exchange, self._period, self._days, 
                                  self._sum._open, self._sum._high, self._sum._low, self._sum._close, 
                                  self._sum._volume)
                
        except BaseException, e:
            print("ChartResults.Get Error %s", e)
            
